#!usr/bin/python
import random
import tkinter as tk
import tkinter.font as tkFont

class cell:
    def __init__(self, width, height, frame, state):
        self.state = state
        self.entity = tk.Button(frame, width=width, height=height, relief=tk.SUNKEN,
                                bg="lightgrey", activebackground="lightgrey")
        self.go = self.state
        self.turn()
        
    def Pack(self):
        self.entity.pack(side=tk.LEFT)
    
    def Check(self,n):
        x=0
        for i in n:
            x+=i
        if self.state:
            if x==1 or x>3:
                self.go=not self.go
            return
        else:
            if x>=2 and x<=3:
                self.go=not self.go
            return
    
    def turn(self):
        self.state = not self.state
        self.go = self.state
        if self.state:
            self.entity.configure(bg="dodgerblue", activebackground="deepskyblue")
        else:
            self.entity.configure(bg="paleturquoise", activebackground="lightcyan")
        
def main():
    top=tk.Tk()
    top.title("LifeGame")
    top.resizable(False,False)
    gf=tkFont.Font(top, family="Arial", size = 15)
    
    cells=[]
    for i in range(0,12):
        frame=tk.Frame(top)
        frame.pack()
        n=[cell(1,1,top,0)]
        for j in range(0,10):
            x=random.randint(-3,2)
            if i==0 or i==11:
                x=-10
            a=cell(1,1,frame,x)
            if x!=-10:
                a.Pack()
            n.append(a)
        n.append(cell(1,1,top,0))
        cells.append(n)
    def Update():
        for i in range(0,len(cells)-1):
            for j in range(0,len(cells[i])-1):
                n=[bool(cells[i-1][j-1].state), bool(cells[i][j-1].state), bool(cells[i+1][j-1].state),
                   bool(cells[i-1][j].state), bool(cells[i+1][j].state),
                   bool(cells[i-1][j+1].state), bool(cells[i][j+1].state), bool(cells[i+1][j+1].state)]
#                print(n)
                cells[i][j].Check(n)
        for i in range(0,len(cells)-1):
            for j in range(0,len(cells[i])-1):
                if cells[i][j].go!=cells[i][j].state:
                    cells[i][j].turn()
    
    nextbtn=tk.Button(top,text="下一个",command=Update,font=gf)
    nextbtn.pack(side=tk.BOTTOM)
    
    top.mainloop()

if __name__ == "__main__":
    main()